<?php

namespace app\admin\controller;

use app\admin\model\AdminModel;
use app\admin\model\RoleModel;
use think\Request;

class Admin extends Base
{
    /**
     * 管理员列表页面
     * @return \think\response\View
     */
    public function index()
    {
        return view('admin/index');
    }

    /**
     * 管理员列表
     * @param Request $request
     * @return \think\response\Json
     */
    public function lists(Request $request)
    {
        return AdminModel::lists($request->param());
    }

    /**
     * 管理员创建页面
     * @return \think\response\View
     */
    public function create()
    {
        $roles = RoleModel::field('id,name')->where('status', 1)->select();
        return view('admin/create', compact('roles'));
    }

    /**
     * 管理员创建
     * @param Request $request
     * @return \think\response\Json
     */
    public function createSubmit(Request $request)
    {
        $flag = $this->validate($request->param(), [
            'role_id' => 'require',
            'username' => 'require|length:5,20',
            'password' => 'require|length:5,20',
            'mobile' => 'mobile',
            'email' => 'email',
            'status' => 'require|in:1,0',
        ]);
        if ($flag !== true) {
            return baseResponse(1, $flag);
        }
        return AdminModel::createSubmit($request->param());
    }

    /**
     * 管理员删除
     * @param int $id 管理员ID
     * @return \think\response\Json
     */
    public function delete($id)
    {
        if (AdminModel::destroy($id)) {
            return baseResponse(0, '删除成功');
        }
        return baseResponse(1, '删除失败');
    }

    /**
     * 管理员编辑页面
     * @return \think\response\View
     */
    public function update($id)
    {
        $admin = AdminModel::find($id);
        $roles = RoleModel::field('id,name')->where('status', 1)->select();
        return view('admin/update', compact('admin', 'roles'));
    }

    /**
     * 管理员编辑页面
     * @param Request $request
     * @param int $id 管理员ID
     * @return \think\response\Json
     */
    public function updateSubmit(Request $request, $id)
    {
        $flag = $this->validate($request->param(), [
            'username' => 'require|length:5,20',
            'password' => 'length:5,20',
            'mobile' => 'mobile',
            'email' => 'email',
            'status' => 'require|in:1,0',
        ]);
        if ($flag !== true) {
            return baseResponse(1, $flag);
        }
        return AdminModel::updateSubmit($request->param(), $id);
    }
}
